import { useRef, useEffect, useState } from "react";
import TopBar from "./TopBar";
import MessagePanel from "./MessagePanel";
import InputBar from "./InputBar";
import type { Message, Contact } from "../types";

interface ChatPanelProps {
  groupName: string;
  messages: Message[];
  contacts: Record<string, Contact>;
  currentUserId: string;
  onSendMessage: (content: string) => void;
}

export default function ChatPanel({
  groupName,
  messages,
  contacts,
  currentUserId,
  onSendMessage,
}: ChatPanelProps) {
  const [inputHeight, setInputHeight] = useState(0);
  const messagesContainerRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    if (messagesContainerRef.current) {
      messagesContainerRef.current.scrollTop =
        messagesContainerRef.current.scrollHeight;
    }
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const handleInputHeightChange = (height: number) => {
    setInputHeight(height);
    setTimeout(() => scrollToBottom(), 50);
  };

  return (
    <div className="flex flex-col h-screen bg-white relative">
      <TopBar groupName={groupName} />
      <div
        ref={messagesContainerRef}
        className="flex-1 overflow-y-auto"
        style={{ height: `calc(100vh - 3rem - ${inputHeight}px)` }}
      >
        <MessagePanel
          messages={messages}
          contacts={contacts}
          currentUserId={currentUserId}
        />
      </div>
      <InputBar
        onSendMessage={onSendMessage}
        onHeightChange={handleInputHeightChange}
      />
    </div>
  );
}
